package com.itfreer.gather.main.fragment;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.FeatureTable;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.esri.arcgisruntime.geometry.Polygon;
import com.esri.arcgisruntime.layers.FeatureLayer;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.itfreer.arcgis.layer.LayerLoader;
import com.itfreer.arcgis.layer.LayerSelect;
import com.itfreer.arcgis.query.QueryListener;
import com.itfreer.arcgis.utils.FeatureTableUtils;
import com.itfreer.arcgis.utils.MapUtils;
import com.itfreer.data.metadata.MetadataService;
import com.itfreer.data.metadata.entity.MetadataValue;
import com.itfreer.gather.R;
import com.itfreer.gis.datasyn.entity.ProjectEntity;
import com.itfreer.utils.common.LogUtils;
import com.itfreer.utils.common.StringUtils;
import com.itfreer.utils.common.ToastUtils;
import com.itfreer.utils.config.ConfigManager;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 分析
 */
@SuppressLint("ValidFragment")
public class AnalyseFragment extends Fragment {

    private PieChart mPieChart;
    private MapView mMapView;
    private View view;

    /**
     * 定义无参构造方法
     */
    public AnalyseFragment() {
    }

    /**
     * 定义带参的构造方法
     *
     * @param mapView
     */
    public AnalyseFragment(MapView mapView) {
        this.mMapView = mapView;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.main_fragment_analyse, container, false);

//        // 空白处时，关闭当前对象
//        view.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                AnalyseFragment.this.getActivity().getFragmentManager().popBackStack();
//            }
//        });

        init();

        return view;
    }

    private void init(){
        final Map<String,Float> dlMap = new HashMap<String,Float>();

        final FeatureLayer dataFeatureLayer = MapUtils.GetFeatureLayerByName(mMapView,"ZY_LDGX_2018_2000");
        if (dataFeatureLayer == null) {
            ToastUtils.showShort(ConfigManager.getContext(),"没有可分析的图层");
            return;
        }

        if(LayerSelect.instance.getSelectedFeatures().size()<=0){
            ToastUtils.showShort(ConfigManager.getContext(),"请选择一个要素进行分析");
            return;
        }

        FeatureTable featureTable = dataFeatureLayer.getFeatureTable();
        Geometry tempGeo = LayerSelect.instance.getSelectedFeatures().get(0).getGeometry();
        tempGeo = GeometryEngine.project(tempGeo, mMapView.getSpatialReference());
        final Geometry geometry = tempGeo;

        FeatureTableUtils.Query(featureTable, "", geometry, new QueryListener() {
            @Override
            public void execute(FeatureTable featureTable1, List<Feature> data) {
                if (data == null || data.size() == 0){
                    ToastUtils.showLong(ConfigManager.getContext(),"分析数据结果为空");
                    return;
                }
                try {
                    for (Integer i = 0; i < data.size(); i++) {
                        //获取所有要素数据
                        Map<String, Object> featureAttributes = data.get(i).getAttributes();
                        // 属性值转换
                        Map<String, MetadataValue> attributes = null;
                        ProjectEntity config = LayerLoader.instance.getConfig(dataFeatureLayer);
                        if(config!=null && config.getMetadata()!=null && !config.getMetadata().equals("")){
                            attributes = MetadataService.instance.convert(config.getMetadata(), featureAttributes);
                        }else{
                            attributes = MetadataService.instance.convert(null, featureAttributes);
                        }

                        // 当前地图要素
                        Geometry itemGeo = GeometryEngine.project(data.get(i).getGeometry(), mMapView.getSpatialReference());

                        //获取交叉图形
                        Geometry insGeometry = GeometryEngine.intersection(geometry, itemGeo);
                        //获取交叉面积 平方米
                        Double insGeometryArea = GeometryEngine.area((Polygon) insGeometry);
                        Float mjMi = Float.parseFloat(insGeometryArea.toString());
                        mjMi = mjMi / 10000; //单位公顷
                        mjMi = Math.round(mjMi*10000)/10000F; // 4位小数

                        //填充地类数据
                        setCharData(dlMap, attributes, mjMi);

                        /* //要素面积
                        Double featureArea = GeometryEngine.area((Polygon) itemGeo);
                        //交叉面积四舍五入
                        featureArea = new BigDecimal(featureArea).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        //面积占比
                        Double area = (insGeometryArea / featureArea) * 100;
                        //面积占比 NF.format(area) + "%"
                        area = new BigDecimal(area).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();*/

                        //小班详情
                        //fatureDetails(attributes,insGeometryArea);
                    }

                    if(dlMap.size()< 1 || dlMap.isEmpty()){
                        ToastUtils.showLong(ConfigManager.getContext(),"无数据可统计");
                    }else{
                        //生成统计图
                        generateChart(dlMap);
                        //生成统计表
                        generateTable(dlMap);
                    }
                }
                catch (SQLException e) {
                    LogUtils.Print("Error in FeatureQueryResult: " + e.getMessage(), LogUtils.Lever.Error);
                    ToastUtils.showLong(ConfigManager.getContext(), "SQL异常！");
                };
            }
        });
    }

    private void setData(ArrayList<PieEntry> entries) {
        PieDataSet dataSet = new PieDataSet(entries, "按地类面积占比");
        dataSet.setSliceSpace(3f);
        dataSet.setSelectionShift(5f);

        //数据和颜色
        ArrayList<Integer> colors = new ArrayList<Integer>();
        for (int c : ColorTemplate.VORDIPLOM_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.JOYFUL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.COLORFUL_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.LIBERTY_COLORS) {
            colors.add(c);
        }
        for (int c : ColorTemplate.PASTEL_COLORS) {
            colors.add(c);
        }
        colors.add(ColorTemplate.getHoloBlue());
        dataSet.setColors(colors);
        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.BLACK);
        mPieChart.setData(data);
        mPieChart.highlightValues(null);
        //刷新
        mPieChart.invalidate();
    }

    /**
     *
     * @param map
     * @param attributes 要素属性数据
     * @param insGeometryArea 相交面积
     */
    private void setCharData(Map<String, Float> map, Map<String, MetadataValue> attributes, Float insGeometryArea) {
        //含有地类
        if(!attributes.containsKey("DI_LEI")){
            return;
        }

        MetadataValue metadatavalue = attributes.get("DI_LEI");
        //获取地类字典
        String dlDesc = metadatavalue.getDictionaryValue();
        if(map.containsKey(dlDesc)){
            Float value = map.get(dlDesc);
            map.put(dlDesc, value + insGeometryArea);
        }else{
            map.put(dlDesc, insGeometryArea);
        }
    }

    /**
     * 生成统计图
     * @param dlMap
     */
    private void generateChart( Map<String,Float> dlMap){
        mPieChart = view.findViewById(R.id.analyse_chart);

        //饼状图
        mPieChart.setUsePercentValues(true);
        mPieChart.getDescription().setEnabled(false);
        mPieChart.setExtraOffsets(5, 10, 5, 5);

        mPieChart.setDragDecelerationFrictionCoef(0.95f);
//        //设置中间文件
//        mPieChart.setCenterText(generateCenterSpannableText());

        mPieChart.setDrawHoleEnabled(true);
        mPieChart.setHoleColor(Color.WHITE);

        mPieChart.setTransparentCircleColor(Color.WHITE);
        mPieChart.setTransparentCircleAlpha(110);

        mPieChart.setHoleRadius(38f);
        mPieChart.setTransparentCircleRadius(38f);

        mPieChart.setDrawCenterText(true);

        mPieChart.setRotationAngle(0);
        // 触摸旋转
        mPieChart.setRotationEnabled(true);
        mPieChart.setHighlightPerTapEnabled(true);

        //生成统计表数据
        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        for (Map.Entry<String, Float> entry : dlMap.entrySet()) {
            PieEntry pieEntry = new PieEntry(entry.getValue(),entry.getKey());
            entries.add(pieEntry);
        }

        //模拟数据
        /*entries.add(new PieEntry(40, "纯林地"));
        entries.add(new PieEntry(20, "未成林造林地"));
        entries.add(new PieEntry(30, "其它灌木林地"));
        entries.add(new PieEntry(10, "非林地"));*/

        //设置数据
        setData(entries);

        mPieChart.animateY(1400, Easing.EasingOption.EaseInOutQuad);
        Legend l = mPieChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);
        l.setDrawInside(false);
        l.setXEntrySpace(7f);
        l.setYEntrySpace(0f);
        l.setYOffset(0f);

        // 输入标签样式
        mPieChart.setEntryLabelColor(Color.BLACK);
        mPieChart.setEntryLabelTextSize(12f);
    }

    /***
     * 生成统计表
     * @param dlMap
     */
    private void generateTable( Map<String,Float> dlMap){

        TableLayout tableLayout = (TableLayout) view.findViewById(R.id.analyseTable);
        //可伸缩扩展
        tableLayout.setStretchAllColumns(true);
        //移除所有表内容
        //tableLayout.removeAllViews();

        LinearLayout.LayoutParams tbPm = new TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT,30);

        //创建表头
        TableRow tableHead= new TableRow(getActivity());
        tableHead.setDividerDrawable(getActivity().getDrawable(R.drawable.table_line2));
        tableHead.setShowDividers(TableRow.SHOW_DIVIDER_BEGINNING|TableRow.SHOW_DIVIDER_MIDDLE|TableRow.SHOW_DIVIDER_END);
        tableHead.setBackground(new ColorDrawable(Color.parseColor("#FFF8F8F8")));

        //添加TextView控件
        TextView thv1 = new TextView(getActivity());
        thv1.setText("地类");
        thv1.setGravity(Gravity.CENTER);
        tableHead.addView(thv1);
        //添加TextView控件
        TextView thv2= new TextView(getActivity());
        thv2.setText("面积(公顷)");
        thv2.setGravity(Gravity.CENTER);
        tableHead.addView(thv2);
        //添加表头
        tableLayout.addView(tableHead,tbPm);

        //循环生成表格
        for (Map.Entry<String, Float> entry : dlMap.entrySet()) {
            //创建tableRow对象
            TableRow tableBody= new TableRow(getActivity());
            //newTableRow.setc
            tableBody.setDividerDrawable(getActivity().getDrawable(R.drawable.table_line2));
            tableBody.setShowDividers(TableRow.SHOW_DIVIDER_BEGINNING|TableRow.SHOW_DIVIDER_MIDDLE|TableRow.SHOW_DIVIDER_END);

            //添加TextView控件
            TextView tv1 = new TextView(getActivity());
            tv1.setText(entry.getKey());
            tv1.setGravity(Gravity.CENTER);
            tableBody.addView(tv1);

            //添加TextView控件
            TextView tv2= new TextView(getActivity());
            tv2.setText(entry.getValue().toString());
            tv2.setGravity(Gravity.CENTER);
            tableBody.addView(tv2);

            tableLayout.addView(tableBody,tbPm);
        }
    }

//    /**
//     * 小班详情
//     * @param map
//     */
//    private void fatureDetails(Map<String, MetadataValue> map,Double insGeometryArea ){
//
//        if(map == null || map.isEmpty()){
//            return;
//        }
//
//        //获取父LinearLayout对象
//        LinearLayout pLin = (LinearLayout) view.findViewById(R.id.analyseDetails);
//        //子LinearLayout对象样式参数
//        LinearLayout.LayoutParams cllPm = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//        cllPm.setMargins(10, 10, 10, 10);
//
//        //定义TextView1样式参数
//        LinearLayout.LayoutParams tvPm1 = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//
//        //创建TableLayout样式参数
//        LinearLayout.LayoutParams tlPm = new TableLayout.LayoutParams(
//                TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
//        tlPm.setMargins(0,5,0,0);
//
//        //创建TableRow样式参数
//        LinearLayout.LayoutParams trPm = new TableRow.LayoutParams(
//                TableRow.LayoutParams.MATCH_PARENT,TableRow.LayoutParams.WRAP_CONTENT);
//
//        //定义TextView6样式参数
//        LinearLayout.LayoutParams tvPm6 = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
//        tvPm6.setMargins(0,5,0,0);
//
//        //Veiw对象样式参数
//        LinearLayout.LayoutParams vPm = new LinearLayout.LayoutParams(
//                LinearLayout.LayoutParams.MATCH_PARENT,1);
//        vPm.setMargins(10, 0, 10, 0);
//        vPm.gravity = Gravity.CENTER;
//
//        //创建子LinearLayout对象
//        LinearLayout cLin = new LinearLayout(getActivity());
//        cLin.setOrientation(LinearLayout.VERTICAL);
//
//        //创建第一个TextView对象
//        com.itfreer.ui.base.TextView tv1 = new com.itfreer.ui.base.TextView(getActivity());
//        String[] str = {"SHI","XIAN","LIN_YE_JU","LIN_CHANG","XIAO_BAN"};
//        tv1.setText(getSplicText(map, str));
//        tv1.setTextColor(Color.parseColor("#FF4A4A4A"));
//        tv1.setTextSize(16);
//        tv1.setLayoutParams(tvPm1);
//        cLin.addView(tv1);
//
//        //创建TableLayout对象
//        TableLayout tableLayout = new TableLayout(getActivity());
//
//        //创建第一个TableRow对象
//        TableRow tr1= new TableRow(getActivity());
//        //创建第二个TextView控件
//        TextView tv2 = new TextView(getActivity());
//        tv2.setText("小班面积(公顷)："+getSingleText(map,"MIAN_JI"));
//        tv2.setGravity(Gravity.LEFT);
//        tr1.addView(tv2);
//
//        java.text.NumberFormat NF = java.text.NumberFormat.getInstance();
//        NF.setGroupingUsed(false);
//
//        //添加第三个TextView控件
//        TextView tv3= new TextView(getActivity());
//        tv3.setText("占比面积(公顷)："+ NF.format(insGeometryArea));
//        tv3.setGravity(Gravity.LEFT);
//        tr1.addView(tv3);
//        //添加第一个TableRow对象
//        tableLayout.addView(tr1,trPm);
//
//        //创建第二个TableRow对象
//        TableRow tr2= new TableRow(getActivity());
//        //添加第四个TextView控件
//        TextView tv4 = new TextView(getActivity());
//        tv4.setText("地类："+getSingleText(map,"DI_LEI"));
//        tv4.setGravity(Gravity.LEFT);
//        tr2.addView(tv4);
//        //添加第五个TextView控件
//        TextView tv5= new TextView(getActivity());
//        tv5.setText("林种："+getSingleText(map,"LIN_ZHONG"));
//        tv5.setGravity(Gravity.LEFT);
//        tr2.addView(tv5);
//        ///添加第二个TableRow对象
//        tableLayout.addView(tr2,trPm);
//        //子LinearLayout对象添加ableLayout
//        cLin.addView(tableLayout,tlPm);
//
//        //创建第六个TextView对象
//        com.itfreer.ui.base.TextView tv6 = new com.itfreer.ui.base.TextView(getActivity());
//        tv6.setText("详情");
//        tv6.setTextColor(Color.parseColor("#FF66708D"));
//        tv6.setTextSize(16);
//        tv6.setLayoutParams(tvPm6);
//        cLin.addView(tv6);
//        //父LinearLayout对象添加子LinearLayout
//        pLin.addView(cLin,cllPm);
//
//        //创建 View 对象
//        View v = new View(getActivity());
//        v.setBackground(new ColorDrawable(Color.parseColor("#FFE3E3E3")));
//        pLin.addView(v,vPm);
//    }

    /***
     * 获取拼接的内容
     * @param map
     * @return
     */
    private String getSplicText(Map<String, MetadataValue> map,String[] strArr){
        String text = "";
        if(strArr.length < 1){
            return "";
        }
        for(int i=0;i<strArr.length;i++){
            if(map.containsKey(strArr[i])){
                String docVlue = map.get(strArr[i]).getDictionaryValue();
                if(StringUtils.IsNullOrEmpty(docVlue)){
                    String value = map.get(strArr[i]).getValue().toString();
                    if(!StringUtils.IsNullOrEmpty(value)){
                        text += value+"-";
                    }
                }else{
                    text += docVlue+"-";
                }
            }
        }

        if(text.length()>1){
            text = text.substring(0,text.length()-1);
        }
        return text;
    }

    /***
     * 获取单个字段的内容
     * @param map
     * @return
     */
    private String getSingleText(Map<String, MetadataValue> map,String strArr){
        String text = "";
        if(map.containsKey(strArr)){
            String docVlue = map.get(strArr).getDictionaryValue();
            if(StringUtils.IsNullOrEmpty(docVlue)){
                String value = map.get(strArr).getValue().toString();
                if(!StringUtils.IsNullOrEmpty(value)){
                    text = value;
                }
            }else{
                text = docVlue;
            }
        }
        return text;
    }
}
